package mysql;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* Created by nuno-rafael-figueiredo on 02-07-2014.
*/
public class Connection {
    public static final int DEFAULT_PORT = 3306;

    private final String hostname;
    private final int port;
    private final String user;
    private final String password;
    private final String schemaName;
    private java.sql.Connection connection;

    public Connection(String hostname, int port, String user, String password, String schemaName) {
        this.hostname = hostname;
        this.port = port;
        this.user = user;
        this.password = password;
        this.schemaName = schemaName;
    }

    public Connection(String hostname, String user, String password, String schemaName) {
        this(hostname, DEFAULT_PORT, user, password, schemaName);
    }

    public String getHostname() {
        return hostname;
    }

    public int getPort() {
        return port;
    }

    public String getUser() {
        return user;
    }

    public String getPassword() {
        return password;
    }

    public String getSchemaName() {
        return schemaName;
    }

    @Override
    public String toString() {
        return String.format("%s@%s:%d/%s",
                user,
                hostname,
                port,
                schemaName
        );
    }

    public String getUrl() {
        return String.format("jdbc:mysql://%s:%04d/%s?user=%s&password=%s",
                hostname,
                port,
                schemaName,
                user,
                password
        );
    }

    public void connect() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(getUrl());
    }

    public void close() throws SQLException {
        connection.close();
    }

    public boolean execute(String sql) throws SQLException {
        return createStatement().execute(sql);
    }

    private Statement createStatement() throws SQLException {
        return connection.createStatement();
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        return createStatement().executeQuery(sql);
    }

    public Schema extract() {
        Schema schema = new Schema(this);
        schema.extract();
        return schema;
    }
}
